package org.jeecg.modules.hc.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.base.Joiner;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.hc.entity.*;
import org.jeecg.modules.hc.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;

/**
 * @Description: 售后
 * @Author: jeecg-boot
 * @Date: 2022-12-13
 * @Version: V1.0
 */
@Api(tags = "售后")
@RestController
@RequestMapping("/hc/hcAfterSales")
@Slf4j
public class HcAfterSalesController extends JeecgController<HcAfterSales, IHcAfterSalesService> {
    @Autowired
    private IHcCompanyPickupAddressService companyPickupAddressService;
    @Autowired
    private IHcAfterSalesService hcAfterSalesService;
    @Autowired
    private IHcCompanyFoodOrderService hcCompanyFoodOrderService;
    @Autowired
    private IHcCompanyMerchantAfterSalesService hcCompanyMerchantAfterSalesService;
    @Autowired
    private IHcCompanyMerchantSettingService companyMerchantSettingService;
    @Autowired
    private IHcCompanyInfoService companyInfoService;
    @Autowired
    private IHcMerchantService merchantService;
    @Autowired
    private RedisUtil redisUtil;

    @ApiOperation("获取商家售后订单")
    @GetMapping(value = "/getMerchantList")
    public Result<IPage<HcAfterSales>> getMerchantList(HcAfterSales param,
                                                       @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) throws ParseException {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        param.setMerchantId(sysUser.getId());

        if (StringUtils.isNotBlank(param.getTimeBegin())) {
            Date parse = DateUtils.parseDate(param.getTimeBegin(), "yyyy年MM月dd日");
            String beginTime = "";
            String endTime = DateUtils.formatDate(parse, "yyyy-MM-dd") + " 18:00:00";

            Calendar instance = Calendar.getInstance();
            instance.setTime(parse);
            instance.add(Calendar.DAY_OF_MONTH, -1);
            beginTime = DateUtils.formatDate(instance.getTime(), "yyyy-MM-dd") + " 18:00:01";

            param.setTimeBegin(beginTime);
            param.setTimeEnd(endTime);
        }

        Page<HcAfterSales> page = new Page<HcAfterSales>(pageNo, pageSize);
        IPage<HcAfterSales> pageList = hcAfterSalesService.getMerchantList(page, param);

        for (HcAfterSales record : pageList.getRecords()) {
            hcAfterSalesService.setInformation(record);
        }
        return Result.OK(pageList);
    }

    /**
     * 分页列表查询
     *
     * @param hcAfterSales
     * @param pageNo
     * @param pageSize
     * @return
     */
    //@AutoLog(value = "售后-分页列表查询")
    @ApiOperation(value = "售后-分页列表查询", notes = "售后-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<HcAfterSales>> queryPageList(HcAfterSales hcAfterSales,
                                                     @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                     @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<HcAfterSales> page = new Page<>(pageNo, pageSize);
        IPage<HcAfterSales> pageList = hcAfterSalesService.pageList(page, hcAfterSales);
        return Result.OK(pageList);
    }



    /**
     * 分页列表查询
     *
     * @param hcAfterSales
     * @param pageNo
     * @param pageSize
     * @return
     */
    //@AutoLog(value = "售后-分页列表查询")
    @ApiOperation(value = "售后-分页列表查询", notes = "售后-分页列表查询")
    @GetMapping(value = "/listNew")
    public Result<IPage<HcAfterSales>> queryPageListNew(HcAfterSales hcAfterSales,
                                                     @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                     @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
//        Page<HcAfterSales> page = new Page<>(pageNo, pageSize);
//        IPage<HcAfterSales> pageList = hcAfterSalesService.pageList(page, hcAfterSales);
//        List<HcAfterSales> records = pageList.getRecords();
        // 从缓存中获取数据
//        List<HcAfterSales> afterSales = (List<HcAfterSales>) redisUtil.get(RedisConstant.HC_ORDER_ALL);
//        if (CollectionUtils.isEmpty(afterSales)){
//            afterSales = hcAfterSalesService.list();
//            redisUtil.set(RedisConstant.HC_ORDER_ALL,afterSales);
//        }
        Page<HcAfterSales> page = new Page<>(pageNo, 9999999);
        List<HcAfterSales> afterSales = hcAfterSalesService.pageList(page,hcAfterSales).getRecords();
        //添加企业售后
        List<HcCompanyMerchantAfterSales> all = hcCompanyMerchantAfterSalesService.list();
        List<HcAfterSales> companyAfterSales = new ArrayList<>();
        all.forEach(a -> {
            List<String> foodName = new ArrayList<>();
            HcAfterSales companySales = new HcAfterSales().setId(a.getId());
            HcOrderMerchant hcOrderMerchant = new HcOrderMerchant();
            String orderCompanyId = a.getOrderCompanyId();
            //价格
            BigDecimal foodPrice = new BigDecimal(0);
            if (orderCompanyId.contains(",")){
                List<String> ids = Arrays.asList(orderCompanyId.split(","));
                List<HcCompanyFoodOrder> hcCompanyFoodOrders = hcCompanyFoodOrderService.list(new LambdaQueryWrapper<HcCompanyFoodOrder>().in(HcCompanyFoodOrder::getId, ids));

                hcOrderMerchant.setUserId(hcCompanyFoodOrders.get(0).getUserId());
                hcOrderMerchant.setMerchantId(hcCompanyFoodOrders.get(0).getMerchantId());
                //公司信息
                HcCompanyInfo companyInfo = companyInfoService.getOne(new LambdaQueryWrapper<HcCompanyInfo>().eq(HcCompanyInfo::getId, hcCompanyFoodOrders.get(0).getCompanyId()));
                hcOrderMerchant.setCompanyName(companyInfo.getCompanyName());

                hcOrderMerchant.setPickingSerialNo(hcCompanyFoodOrders.get(0).getPickingSerialNo());
                hcOrderMerchant.setNameTakingMeal(hcCompanyFoodOrders.get(0).getUsername());

                HcCompanyPickupAddress pickupAddress = companyPickupAddressService.getOne(new LambdaQueryWrapper<HcCompanyPickupAddress>().eq(HcCompanyPickupAddress::getId, hcCompanyFoodOrders.get(0).getPickupAddressId()));
                hcOrderMerchant.setPickingAddress(companyInfo.getCompanyName()+companyInfo.getCompanyAddress()+pickupAddress.getPickupAddress());
                hcOrderMerchant.setSupplyAddress(hcCompanyFoodOrders.get(0).getAddressCode());
                for (HcCompanyFoodOrder hcCompanyFoodOrder : hcCompanyFoodOrders) {
                    JSONObject foodInfo = JSONObject.parseObject(hcCompanyFoodOrder.getFoodInfo());
                    JSONObject foodObject = foodInfo.getJSONObject("food");
                    HcCompanyFoodList hcCompanyFoodList = foodObject.toJavaObject(HcCompanyFoodList.class);
                    //商品数量
                    int foodNum = (int) foodInfo.get("foodNum");
                    foodName.add(hcCompanyFoodList.getFoodName() +"x"+ foodNum);
                    if (hcCompanyFoodList.getCooperatePrice()==null || hcCompanyFoodList.getCooperatePrice().compareTo(new BigDecimal(0)) == 0){
                        //获取门店价格
                        HcCompanyMerchantSetting companyMerchantSetting = companyMerchantSettingService.getOne(new LambdaQueryWrapper<HcCompanyMerchantSetting>()
                                .eq(HcCompanyMerchantSetting::getCompanyId, hcCompanyFoodList.getCompanyId())
                                .eq(HcCompanyMerchantSetting::getMerchantId, hcCompanyFoodList.getMerchantId()));
                        if (null == companyMerchantSetting){
                            companyMerchantSetting = new HcCompanyMerchantSetting().setMerchantCooperatePrice(new BigDecimal(0)).setSalePrice(new BigDecimal(0));
                        }
                        if (companyMerchantSetting.getMerchantCooperatePrice()==null||companyMerchantSetting.getMerchantCooperatePrice().compareTo(new BigDecimal(0))==0){
                            //获取企业合作价格
                            HcCompanyInfo hcCompanyInfo = companyInfoService.getOne(new LambdaQueryWrapper<HcCompanyInfo>().eq(HcCompanyInfo::getId, hcCompanyFoodList.getCompanyId()));
                            foodPrice = foodPrice.add(hcCompanyInfo.getMerchantPrice().multiply(new BigDecimal(foodNum)));
                        }else {
                            foodPrice = foodPrice.add(companyMerchantSetting.getMerchantCooperatePrice().multiply(new BigDecimal(foodNum)));
                        }
                    }else {
                        foodPrice = foodPrice.add(hcCompanyFoodList.getCooperatePrice().multiply(new BigDecimal(foodNum)));
                    }
                }
            }else {
                HcCompanyFoodOrder companyFoodOrder = hcCompanyFoodOrderService.getOne(new LambdaQueryWrapper<HcCompanyFoodOrder>().eq(HcCompanyFoodOrder::getId, orderCompanyId));
                hcOrderMerchant.setUserId(companyFoodOrder.getUserId());
                hcOrderMerchant.setMerchantId(companyFoodOrder.getMerchantId());
                hcOrderMerchant.setPickingSerialNo(companyFoodOrder.getPickingSerialNo());
                hcOrderMerchant.setNameTakingMeal(companyFoodOrder.getUsername());

                //公司信息
                HcCompanyInfo companyInfo = companyInfoService.getOne(new LambdaQueryWrapper<HcCompanyInfo>().eq(HcCompanyInfo::getId, companyFoodOrder.getCompanyId()));
                hcOrderMerchant.setCompanyName(companyInfo.getCompanyName());

                //取餐地址
                String pickupAddressId = companyFoodOrder.getPickupAddressId();
                HcCompanyPickupAddress pickupAddress = companyPickupAddressService.getOne(new LambdaQueryWrapper<HcCompanyPickupAddress>().eq(HcCompanyPickupAddress::getId, pickupAddressId));
                hcOrderMerchant.setPickingAddress(companyInfo.getCompanyName()+companyInfo.getCompanyAddress()+pickupAddress.getPickupAddress());
                hcOrderMerchant.setSupplyAddress(companyFoodOrder.getAddressCode());

                JSONObject foodInfo = JSONObject.parseObject(companyFoodOrder.getFoodInfo());
                JSONObject foodObject = foodInfo.getJSONObject("food");
                HcCompanyFoodList hcCompanyFoodList = foodObject.toJavaObject(HcCompanyFoodList.class);

                //商品数量
                int foodNum = (int) foodInfo.get("foodNum");
                foodName.add(hcCompanyFoodList.getFoodName() +"x"+ foodNum);
                if (hcCompanyFoodList.getCooperatePrice()==null||hcCompanyFoodList.getCooperatePrice().compareTo(new BigDecimal(0)) == 0){
                    //获取门店价格
                    HcCompanyMerchantSetting companyMerchantSetting = companyMerchantSettingService.getOne(new LambdaQueryWrapper<HcCompanyMerchantSetting>()
                            .eq(HcCompanyMerchantSetting::getCompanyId, hcCompanyFoodList.getCompanyId())
                            .eq(HcCompanyMerchantSetting::getMerchantId, hcCompanyFoodList.getMerchantId()));
                    if (null == companyMerchantSetting){
                        companyMerchantSetting = new HcCompanyMerchantSetting().setMerchantCooperatePrice(new BigDecimal(0)).setSalePrice(new BigDecimal(0));
                    }
                    if (companyMerchantSetting.getMerchantCooperatePrice()==null||companyMerchantSetting.getMerchantCooperatePrice().compareTo(new BigDecimal(0))==0){
                        //获取企业合作价格
                        HcCompanyInfo hcCompanyInfo = companyInfoService.getOne(new LambdaQueryWrapper<HcCompanyInfo>().eq(HcCompanyInfo::getId, hcCompanyFoodList.getCompanyId()));
                        foodPrice = foodPrice.add(hcCompanyInfo.getMerchantPrice().multiply(new BigDecimal(foodNum)));
                    }else {
                        foodPrice = foodPrice.add(companyMerchantSetting.getMerchantCooperatePrice().multiply(new BigDecimal(foodNum)));
                    }
                }else {
                    foodPrice = foodPrice.add(hcCompanyFoodList.getCooperatePrice().multiply(new BigDecimal(foodNum)));
                }
            }
            companySales.setFeedback(a.getFeedback());
            companySales.setFoodProblems(a.getFoodProblems());
            companySales.setPicture(a.getPicture());
            companySales.setProcessingTime(a.getProcessingTime());
            companySales.setState(a.getState());
            companySales.setStoreName(merchantService.getOne(new LambdaQueryWrapper<HcMerchant>().eq(HcMerchant::getId,a.getMerchantId())).getStoreName());
            companySales.setCompanyId(a.getCompanyId());
            companySales.setMerchantId(a.getMerchantId());
            companySales.setDeductMerchantAmount(a.getDeductMerchantAmount());
            //总价格
            companySales.setTotalPrice(foodPrice);
            //菜品名
            companySales.setNameDishes(foodName.size()>1? Joiner.on("+").join(foodName) :foodName.get(0));
            //投诉次数
            List<HcCompanyMerchantAfterSales> list = hcCompanyMerchantAfterSalesService.list(new LambdaQueryWrapper<HcCompanyMerchantAfterSales>()
                    .eq(HcCompanyMerchantAfterSales::getMerchantId, a.getMerchantId()));
            companySales.setComplaintCount((long) list.size());

            companySales.setHcOrderMerchant(hcOrderMerchant);
            companySales.setCreateTime(a.getCreateTime());
            companyAfterSales.add(companySales);
        });

        afterSales.addAll(companyAfterSales);
        afterSales.sort(new Comparator<HcAfterSales>() {
            @Override
            public int compare(HcAfterSales o1, HcAfterSales o2) {
                return o2.getCreateTime().compareTo(o1.getCreateTime());
            }
        });

        int totalRecords = afterSales.size() + all.size(); // 计算总记录数
        // 创建一个 Page 对象，并设置总记录数、每页记录数、当前页数
        IPage<HcAfterSales> pageList = new Page<>(pageNo, pageSize, totalRecords);
         // 计算分页起始索引和结束索引
        int startIndex = (pageNo - 1) * pageSize;
        int endIndex = Math.min(startIndex + pageSize, afterSales.size());
         // 截取需要的分页数据
        List<HcAfterSales> pageData = afterSales.subList(startIndex, endIndex);
        for (HcAfterSales data : pageData) {
            if (StringUtils.isEmpty(data.getCompanyId())){
                hcAfterSalesService.setInformation(data);
            }
        }
        // 设置分页数据
        pageList.setRecords(pageData);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param hcAfterSales
     * @return
     */
    @AutoLog(value = "售后-添加")
    @ApiOperation(value = "售后-添加", notes = "售后-添加")
    //@RequiresPermissions("org.jeecg.modules:hc_after_sales:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody HcAfterSales hcAfterSales) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        hcAfterSales.setUserId(sysUser.getId());
        hcAfterSalesService.add(hcAfterSales);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param hcAfterSales
     * @return
     */
    @AutoLog(value = "售后-编辑")
    @ApiOperation(value = "售后-编辑", notes = "售后-编辑")
    //@RequiresPermissions("org.jeecg.modules:hc_after_sales:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody HcAfterSales hcAfterSales) {
        hcAfterSalesService.edit(hcAfterSales);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
//    @AutoLog(value = "售后-通过id删除")
//    @ApiOperation(value = "售后-通过id删除", notes = "售后-通过id删除")
    //@RequiresPermissions("org.jeecg.modules:hc_after_sales:delete")
//    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        hcAfterSalesService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
//    @AutoLog(value = "售后-批量删除")
//    @ApiOperation(value = "售后-批量删除", notes = "售后-批量删除")
    //@RequiresPermissions("org.jeecg.modules:hc_after_sales:deleteBatch")
//    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.hcAfterSalesService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "售后-通过id查询")
    @ApiOperation(value = "售后-通过id查询", notes = "售后-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<HcAfterSales> queryById(@RequestParam(name = "id", required = true) String id) {
        HcAfterSales hcAfterSales = hcAfterSalesService.getById(id);
        if (hcAfterSales == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(hcAfterSales);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param hcAfterSales
     */
    //@RequiresPermissions("org.jeecg.modules:hc_after_sales:exportXls")
//    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HcAfterSales hcAfterSales) {
        return super.exportXls(request, hcAfterSales, HcAfterSales.class, "售后");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    //@RequiresPermissions("hc_after_sales:importExcel")
//    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, HcAfterSales.class);
    }

}
